package com.example.demo.common;

import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.nio.charset.StandardCharsets;
import java.util.UUID;

/**
 * @author: cheng
 * @date: 2023/6/30 12:49
 * @description: 密码加盐加密
 */
public class PasswordTools {
    /**
     * 密码加盐
     * @param password 明文密码
     * @return 加盐后的密码
     */
    public static String encrypt(String password){
        //1. 产生盐值
        String salt = UUID.randomUUID().toString().replace("-","");
        //2. 将盐值和明文密码结合, 得到加密后的密码
        String finalPassWord = DigestUtils.md5DigestAsHex((salt+password).getBytes());
        //将盐值和加密密码共同返回
        String dbPassword = salt+"$"+finalPassWord;
        return dbPassword;
    }

    /**
     *
     * @param password 明文密码
     * @param salt 盐值
     * @return 加盐后的密码
     */
    public static String encrypt(String password,String salt){
        //1. 将盐值和明文密码结合, 得到加密后的密码
        String finalPassWord = DigestUtils.md5DigestAsHex((salt+password).getBytes());
        //将盐值和加密密码共同返回
        String dbPassword = salt+"$"+finalPassWord;
        return dbPassword;
    }

    /**
     * 验证密码
     * @param password 明文密码
     * @param dbPassword 数据库存储的密码(加盐密码)
     * @return (true 密码正确)/(false 密码错误)
     */
    public static boolean decrypt(String password,String dbPassword){
        boolean result = false;
        if(StringUtils.hasLength(password) && StringUtils.hasLength(dbPassword) &&
                dbPassword.contains("$") && dbPassword.length() == 65){
            //获取盐值
            String[] passwordArr = dbPassword.split("\\$");
            String salt = passwordArr[0];
            //生成验证密码的加盐加密密码
            String check = encrypt(password,salt);
            if(check.equals(dbPassword)){
                result = true;
            }
        }
        return result;
    }

    public static void main(String[] args) {
        String pa = "123456";
        String db = PasswordTools.encrypt(pa);
        String db1 = PasswordTools.encrypt(pa);
        String db2 = PasswordTools.encrypt(pa);
        System.out.println(db);
        System.out.println(db1);
        System.out.println(db2);

        String pw = "12345";
        boolean re = PasswordTools.decrypt(pw,db1);
        System.out.println("错误的"+re);
        String pwd = "123456";
        boolean res = PasswordTools.decrypt(pwd,db1);
        System.out.println("正确的"+res);
    }
}
